package ttot.plugin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;

/**
 * Goal for the ttot plugin
 * 
 * @goal 3to
 * 
 * @phase verify
 * @requiresDependencyResolution test
 */
public class TtotMojo extends AbstractMojo {

	/**
	 * The Project
	 * 
	 * @parameter expression="${project}"
	 */
	MavenProject project;

	public void execute() throws MojoExecutionException {
		List<?> classpathElements;
		try {
			classpathElements = project.getTestClasspathElements();
			ClasspathArchive ca = new ClasspathArchive(classpathElements);
			try {
				FileOutputStream fos = new FileOutputStream(new File(
						project.getBasedir(), "test-output.jar"));
				Date start = new Date();
				ca.writeArchive(fos);
				fos.close();
				Date end = new Date();
				long time = end.getTime() - start.getTime();
				double total = (double) ca.getTotal() / 1024 / 1024;
				double speed = (double) total * 1000 / time;
				getLog().info(String.format("[3to] Compressed test classpath. Total: %.2f MB (%.2f MB/s)", total, speed));
			} catch (IOException e) {
				throw new MojoExecutionException("Cannot write archive", e);
			}
			HashSet<String> duplicateEntries = ca.getDuplicateEntries();
			if (duplicateEntries.size() != 0) {
				getLog().warn(
						"[3to] There were file duplicates that were skipped");
				for (String entry : duplicateEntries) {
					if (!entry.endsWith("/")) {
						List<File> entrySources = ca.getEntrySources(entry);
						if (entrySources.size() < 2) {
							throw new MojoExecutionException(
									"Invalid entrySources size: "
											+ entrySources.size() + " for "
											+ entry);
						}
						getLog().warn(
								"[3to] File: " + entry + " copied from "
										+ entrySources.get(0).getName());
						for (int i = 1; i < entrySources.size(); i++) {
							getLog().warn(
									"[3to] \t" + "Skipped source: "
											+ entrySources.get(i).getName());
						}
					}
				}
			}
		} catch (DependencyResolutionRequiredException e) {
			throw new MojoExecutionException("Cannot read test classpath", e);
		}
	}
}
